package service

import (
	"errors"
	"imooc.com/hello/model"
	"time"
)

type ContactService struct {

}

func (s *ContactService) AddFriend(userId, dstId int64) error {
    //判断是否加的自己
	if userId == dstId {
		return errors.New("不能加自己为好友")
	}
	//判断加的人是否存在
	var dstUser model.User
	_, err := DbEngin.Where("id = ?", dstId).Cols("id").Get(&dstUser)
	if err != nil {
		return err
	}
	if dstUser.Id <= 0 {
		return errors.New("您添加的好友不存在系统中")
	}

	//判断是否已经为好友了
	var contact model.Concat
	DbEngin.Where("owner_id = ? and dst_obj = ? and cate = ?",
		userId, dstId, model.CONCAT_CATE_USER).Cols("id").Get(&contact)
	if contact.Id > 0 {
		return errors.New("该好友已经添加过了")
	}

	//开启一个事务
	session := DbEngin.NewSession()
	session.Begin()
	//userId添加dstId为好友
	err1 := InsertContactOne(userId, dstId, model.CONCAT_CATE_USER)

	//dstId添加userId为好友
	err2 := InsertContactOne(dstId, userId, model.CONCAT_CATE_USER)

	if err1 == nil && err2 == nil {
		session.Commit()
	}else{
		session.Rollback()
		if err1 != nil {
			return err1
		}else if err2 != nil {
			return err2
		}
	}
	return nil
}

func (s *ContactService) LoadFriends(userId int64)([]model.User, error)  {
	if userId <= 0 {
		return nil, errors.New("该用户不存在")
	}
	contacts := make([]model.Concat, 0)
	err := DbEngin.Where("owner_id = ? and cate = ?", userId, model.CONCAT_CATE_USER).
		Cols("dst_obj").Find(&contacts)
	if err != nil {
		return nil, err
	}
	var ids = make([]int64, 0)
	for _, c := range contacts {
		ids = append(ids, c.DstObj)
	}

	result := make([]model.User, 0)
	err = DbEngin.In("id", ids).Find(&result)

	return result, err
}

func InsertContactOne(ownerId, dstObj int64, cate int) error  {

	_, err := DbEngin.InsertOne(model.Concat{
		OwnerId: ownerId,
		DstObj: dstObj,
		Cate: cate,
		CreateAt: time.Now(),
	})

	return err
}

func LoadAllOnlineUserIdsByCommunity(userIds []int64, communityId int64)([]int64, error)  {
	if len(userIds) <= 0 || communityId <= 0  {
		return nil, errors.New("参数错误")
	}
	contacts := make([]model.Concat, 0)
	err := DbEngin.In("owner_id", userIds).
		Where("dst_obj = ? and cate = ?", communityId, model.CONCAT_CATE_COMMUNITY).
		Cols("owner_id").Find(&contacts)
	if err != nil {
		return nil, err
	}

	onlineUserIds := make([]int64, 0)
	if len(contacts) > 0 {
		for _, contact := range contacts {
			onlineUserIds = append(onlineUserIds, contact.OwnerId)
		}
	}
	return onlineUserIds, nil
}